package com.wanxi.servlet;

import com.wanxi.model.Brand;
import com.wanxi.service.BrandService;
import com.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.乱码处理
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
//        2.得到前端的值
        String brandName = req.getParameter("brandName");
        String enterPriseName = req.getParameter("enterPriseName");
        String sort = req.getParameter("sort");
        String brandIntroduce = req.getParameter("brandIntroduce");
        String enable = req.getParameter("enable");
//        3.将数据封装成对象
        Brand brand = Brand.builder()
                .brandIntroduce(brandIntroduce)
                .enterPriseName(enterPriseName)
                .sort(Tool.strToInt(sort))
                .enable(Tool.strToInt(enable))
                .brandName(brandName)
                .build();
//        4.要先处理逻辑关系
        BrandService brandService = new BrandService();
        int count = brandService.add(brand);
        if (count > 0) {
            //        5.新增成功以后，要给前端一个反馈
            req.setAttribute("count", count);
//        req.getRequestDispatcher("/findAll").forward(req, resp);
            resp.sendRedirect("/findAll");
        } else {
            req.setAttribute("model", brand);
//            req.getSession().setAttribute("model", brand);
//            req.getServletContext().setAttribute("model", brand);
//            req.getServletContext().removeAttribute("model");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
//            resp.sendRedirect("/error.jsp");
        }

    }
}
